package net.zjitc.list.web;

import net.zjitc.list.dao.UserDao;
import net.zjitc.list.dao.UserDaoImpl;
import net.zjitc.list.domain.User;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * @Author Administrator
 * @Date 2020/6/16 13:48
 * 添加联系人Servlet
 **/
@WebServlet("/addUserServlet")
public class AddUserServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /* 1、设置request编码utf-8
           2、接收用户所有的请求参数（Map）
           3、利用BeanUtils工具将所有请求参数(map)封装成对象user
           4、调用dao方法完成添加功能
              若添加成功，想看到最新的用户列表，重定向到userListServlet
              若添加失败，提示信息保存在request域，转发到add.jsp（展示错误提示信息）
        * */
        request.setCharacterEncoding("utf-8");
        Map<String, String[]> map = request.getParameterMap();
        User user=new User();
        try {
            /* 将map中数据自动封装到user对象:
            * 前提：map中的key（请求参数的name）与user对象的属性必须一一对应*/
            BeanUtils.populate(user,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        /* 调用dao方法完成添加功能*/
        UserDao dao=new UserDaoImpl();
        int i = dao.add(user);
        if(i>0){
            /*添加成功,重定向*/
            /*项目的发布路径*/
            String contextPath = request.getContextPath();
            response.sendRedirect(contextPath+"/userListServlet");
        }else if(i==0){
            /*添加失败,转发*/
            request.setAttribute("add_error","添加失败");
            request.getRequestDispatcher("/list/add.jsp").forward(request,response);
        }else{
            /* 用户名重复，转发*/
           request.setAttribute("add_error","用户名重复");
           request.getRequestDispatcher("/list/add.jsp").forward(request,response);
        }
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
